package com.gogowan.agroenterprise.supply;

import java.util.List;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.model.IntegrateQuestInfo;
import com.gogowan.agroenterprise.model.Message;
import com.gogowan.agroenterprise.model.MoreDetailResultInfo;
import com.gogowan.agroenterprise.model.SeekSDInfo;
import com.gogowan.agroenterprise.model.SeekSDResultInfo;
import com.gogowan.agroenterprise.model.SupplyDemandInfo;
import com.gogowan.agroenterprise.supply.utils.MyListView;
import com.gogowan.agroenterprise.supply.utils.SupplyAndDemandUtils;
import com.gogowan.agroenterprise.supply.utils.MyListView.OnRefreshListener;
import com.gogowan.agroenterprise.utils.Utils;

/**
 * 搜索结果列表
 * @author Maniac
 * 2012.12.17
 */
public class SearchResultListActivity extends BaseActivity{
	
	private MyListView list;
	private TextView textView;
	private List<SupplyDemandInfo> supplyDemandInfos;
	private BaseAdapter adapter;
	
	private View bottom;
	private TextView bottomtv;
	private ProgressBar progressBar;
	private LinearLayout bottomLinear;
	
	private SharedPreferences preferences;
	private long enterpriseId;
	private int sdType;
	private String keywords;
	private ProgressDialog progressDialog;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.supply_search_results);
		
		list = (MyListView)findViewById(R.id.supply_search_results_list);
		textView = (TextView)findViewById(R.id.supply_search_results_text);
		bottom = LayoutInflater.from(this).inflate(R.layout.itembottom,null);
		bottomtv = (TextView)bottom.findViewById(R.id.item_bottom_progress_tv);
		progressBar = (ProgressBar)bottom.findViewById(R.id.item_bottom_progressBar);
		bottomLinear = (LinearLayout)bottom.findViewById(R.id.item_bottom_ll);
		
		preferences = getSharedPreferences("LoginINfo", MODE_PRIVATE);
		enterpriseId = preferences.getLong("enterpriseid", 0);
		
		Intent intent = getIntent();
		String source = intent.getStringExtra("ResultList");
		
		if (source==null || source.equals("")) {
			return;
		}
		
		sdType = intent.getIntExtra("sdType", 0);
		keywords = intent.getStringExtra("keywords");
		
		SeekSDResultInfo resultInfo = (SeekSDResultInfo)Utils.fromJSON(source, SeekSDResultInfo.class);
		supplyDemandInfos = resultInfo.getSupplyDemandList();
		
		
		adapter = new BaseAdapter() {
			
			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				LayoutInflater inflater=(LayoutInflater)SearchResultListActivity.this.getSystemService(LAYOUT_INFLATER_SERVICE);
				View layout=inflater.inflate(R.layout.supply_list_item,null);
				TextView textView = (TextView)layout.findViewById(R.id.supply_list_item_text);
				textView.setText(supplyDemandInfos.get(position).getTitle());
				return layout;
			}
			
			@Override
			public long getItemId(int position) {
				return position;
			}
			
			@Override
			public Object getItem(int position) {
				return supplyDemandInfos.get(position);
			}
			
			@Override
			public int getCount() {
				return supplyDemandInfos.size();
			}
		};
		
		if (supplyDemandInfos == null || supplyDemandInfos.size() == 0) {
			return;
		} else {
			textView.setVisibility(View.GONE);
			list.setVisibility(View.VISIBLE);
			list.setAdapter(adapter);
			
			SupplyAndDemandUtils.addFooterView(adapter, SearchResultListActivity.this, list, bottom);
		}
		
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				IntegrateQuestInfo integrateQuestInfo = new IntegrateQuestInfo();
				integrateQuestInfo.setEnterpriseID(enterpriseId);
				integrateQuestInfo.setSdID(supplyDemandInfos.get(position-1).getSdID());
				integrateQuestInfo.setSdType(sdType);
				integrateQuestInfo.setMaterialID(supplyDemandInfos.get(position-1).getMaterialID());
				
				progressDialog = ProgressDialog.show(SearchResultListActivity.this,
						getString(R.string.alert_title),
						"正在获取详细信息", true, false);
				GetDetailAsyn getDetailAsyn = new GetDetailAsyn();
				getDetailAsyn.execute(integrateQuestInfo);
				
			}
		});
		
		list.setonRefreshListener(new OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				loadRemainListItem(0,true);
			}
		});
	
		bottomLinear.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				loadRemainListItem(supplyDemandInfos.get(supplyDemandInfos.size() -1).getSdID(),false);
			}
		});
	}
	
	/**
	 * 刷新或获取更多 列表项
	 * @param sdId  获取从sdid以后的数据
	 * @param isRefresh 是不是刷新操作
	 */
	private void loadRemainListItem(long sdId,boolean isRefresh) {
		if (!isRefresh) {
			bottomtv.setText("正在加载更多.....");
			progressBar.setVisibility(View.VISIBLE);
		}
		SeekSDInfo sdInfo = new SeekSDInfo();
		sdInfo.setTypeCode(sdType);
		sdInfo.setKeyWords(keywords);
		sdInfo.setEnterpriseID(enterpriseId);
		sdInfo.setSdID(sdId);
		
		SearchAsyn searchAsyn = new SearchAsyn(isRefresh);
		searchAsyn.execute(sdInfo);
	}
	
	
	/**
	 * 查看详细内容
	 * @author Maniac
	 * 2012.12.17
	 */
	private class GetDetailAsyn extends MyAsyncTask{

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(SearchResultListActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
			} else {
				
				Message message = (Message) Utils.fromJSON((String) res, Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(SearchResultListActivity.this, getString(R.string.analyse_error), Toast.LENGTH_LONG).show();
				} else {
					MoreDetailResultInfo materialResultInfo = (MoreDetailResultInfo)Utils.fromJSON(string, MoreDetailResultInfo.class);
					int result = materialResultInfo.getResult();
					if (result == 8110) {
						Intent intent = new Intent(SearchResultListActivity.this,MaterialDetailActivity.class);
						intent.putExtra("MaterialDetail", string);
						intent.putExtra("sdType", sdType);
						startActivity(intent);
						Utils.randomAnim(SearchResultListActivity.this);
					} else {
						Toast.makeText(SearchResultListActivity.this, materialResultInfo.getResultinfo(), Toast.LENGTH_LONG).show();
					}
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			IntegrateQuestInfo request = (IntegrateQuestInfo)params[0];
			String json = Utils.toJSON(request);
			Message message = new Message(8100, true, json);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}
	}
	
	/**
	 * 搜索异步操作
	 * @author Maniac
	 * 2012.12.17
	 */
	private class SearchAsyn extends MyAsyncTask{

		private boolean isRefresh;
		
		public SearchAsyn(boolean isRefresh) {
			this.isRefresh = isRefresh;
		}
		
		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				if (isRefresh) {
					list.onRefreshComplete();
				}
				Toast.makeText(SearchResultListActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
			} else {
				
				Message message = (Message) Utils.fromJSON((String) res, Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					if (isRefresh) {
						list.onRefreshComplete();
					}
					Toast.makeText(SearchResultListActivity.this, getString(R.string.analyse_error), Toast.LENGTH_LONG).show();
				} else {
					SeekSDResultInfo resultInfo = (SeekSDResultInfo)Utils.fromJSON(string, SeekSDResultInfo.class);
					int result = resultInfo.getResult();
					if (result == 8010) {
						List<SupplyDemandInfo> cInfo = resultInfo.getSupplyDemandList();
						if (isRefresh) {
							if (cInfo == null || cInfo.size() == 0) {
								Toast.makeText(SearchResultListActivity.this, "刷新失败", Toast.LENGTH_LONG).show();
							} else {
								Toast.makeText(SearchResultListActivity.this, "刷新成功", Toast.LENGTH_LONG).show();
								supplyDemandInfos = cInfo;
								if (supplyDemandInfos == null || supplyDemandInfos.size() == 0) {
									Toast.makeText(SearchResultListActivity.this, "刷新失败", Toast.LENGTH_LONG).show();
								} else {
									adapter.notifyDataSetChanged();
								}
							}
							list.onRefreshComplete();
						} else {
							for (int i = 0; i < cInfo.size(); i++) {
								supplyDemandInfos.add(cInfo.get(i));
							}
							
							if (supplyDemandInfos == null || supplyDemandInfos.size() == 0) {
								Toast.makeText(SearchResultListActivity.this, "获取信息失败", Toast.LENGTH_LONG).show();
							} else {
								adapter.notifyDataSetChanged();
							}
							bottomtv.setText("更多");
							progressBar.setVisibility(View.GONE);
						}
						
					} else {
						if (isRefresh) {
							list.onRefreshComplete();
							Toast.makeText(SearchResultListActivity.this, "刷新失败", Toast.LENGTH_LONG).show();
						} else {
							bottomtv.setText("更多");
							progressBar.setVisibility(View.GONE);
							Toast.makeText(SearchResultListActivity.this, "列表内容已全部显示", Toast.LENGTH_LONG).show();
						}
						
					}
				}
			}
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			SeekSDInfo request = (SeekSDInfo)params[0];
			String json = Utils.toJSON(request);
			Message message = new Message(8000, true, json);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}
		
	}
}
